const connection = require('../app/database');
const connections = require("../app/database");

//创建一个users对象
class UsersService {
  async create(user) {
    const {name, password} = user;
    const statement = `INSERT INTO users (name , password)VALUES(?,?);`
    const result = await connection.execute(statement, [name, password]); // returns an array
    console.log('creating user', result);
    // 2. return the new user
    return result[0];
  }

//判断用户是否存在
// const user = await ctx.service.user.findByName(name);
  async getUserByName(name) {
    const statement = `SELECT * FROM users WHERE name = ?;`
    const result = await connections.execute(statement, [name]);
    return result[0];
  }

  async getAvatarById(userId) {
    try {
      const sql = `SELECT * FROM avatar WHERE user_id = ?`;
      const [result] = await connection.execute(sql, [userId]);
      return result[0];
    } catch (e) {
      console.log(e);
      return e;
    }
  }

  async updateAvatarById(userId, avatarId) {
    try {
      console.log(userId, avatarId);
      const sql = `UPDATE users SET avatar_url = ? WHERE id = ?`;
      const [result] = await connection.execute(sql, [avatarId, userId]);
      console.log(result);
      return result;
    } catch (e) {
      console.log(e);
      return e;
    }
  }
}
module.exports = new UsersService();